import { Button, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { PlusIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiNovelTagAll } from "~/api/novel";
import Title from "~/components/ui/title";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { INovelTag } from "~/types/manage/content/config";
import NovelTagModal from "./novel-tag-modal";

export default function NovelTag() {
  const tableHeight = useTableHeight(223);

  const [dataList, setDataList] = useState<INovelTag[]>([]);
  const [editRecord, setEditRecord] = useState<INovelTag | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const _handler = {
    onCancel: () => {
      setEditRecord(null);
      setModalVisible(false);
    },
    onOk: () => {
      setModalVisible(false);
      _fetch.init();
    },
    addNovelTag: async (record?: INovelTag) => {
      setEditRecord(null);
      setModalVisible(true);
    },
    editNovelTag: async (record: INovelTag) => {
      setEditRecord(record);
      setModalVisible(true);
    },
  };

  const _ui: {
    tableColumns: ColumnsType<INovelTag>;
  } = {
    tableColumns: [
      {
        title: "标签名称",
        dataIndex: "label",
        key: "label",
        fixed: "left",
        width: 300,
      },
      {
        title: "描述",
        dataIndex: "desc",
        key: "desc",
      },
      {
        title: "操作",
        key: "action",
        fixed: "right",
        width: 100,
        render: (_, record) => {
          return (
            <div className="flex items-center justify-end gap-2">
              <Button
                type="link"
                size="small"
                onClick={() => _handler.editNovelTag(record)}
              >
                编辑
              </Button>
            </div>
          );
        },
      },
    ],
  };

  const _fetch = {
    init: async () => {
      setLoading(true);
      const resp = await apiNovelTagAll();
      setDataList(resp);
      setLoading(false);
    },
  };

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <>
      <Title
        title="字典配置"
        buttonGroups={[
          <Button
            type="primary"
            onClick={() => {
              _handler.addNovelTag();
            }}
          >
            <PlusIcon size={18} />
            添加标签
          </Button>,
        ]}
      />
      <div className="h-full w-full">
        <Table
          loading={loading}
          scroll={{
            y: tableHeight,
            x: "max-content",
          }}
          rowKey={(item) => item.id}
          columns={_ui.tableColumns}
          dataSource={dataList}
          pagination={false}
        />
      </div>

      <NovelTagModal
        record={editRecord}
        visible={modalVisible}
        onCancel={_handler.onCancel}
        onOk={_handler.onOk}
      />
    </>
  );
}
